package com.jcli.jb51_net.article._175980开关按钮;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

/**
 * @ClassName 开关是否选中
 * @Description TODO
 * @Author li
 * @Data 2023/12/15 9:56
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        JFrame jf = new JFrame("测试窗口");
        jf.setSize(250,250);
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    JPanel panel= new JPanel();

    //创建开关按钮
    JToggleButton toggleButton = new JCheckBox("开关按钮");
    toggleButton.setForeground(Color.cyan);

    //添加按钮状态被改变的监听
    toggleButton.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            //获取事件源，即开关本身
            JToggleButton toggleButton = (JToggleButton) e.getSource();
            toggleButton.setForeground(Color.ORANGE);
            System.out.println(toggleButton.getText()+"是否选中："+toggleButton.isSelected());
        }
    });

    panel.add(toggleButton);
    jf.setContentPane(panel);
    jf.setVisible(true);
    }
}
